package com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity

import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import cn.qqtheme.framework.picker.OptionPicker
import cn.qqtheme.framework.widget.WheelView
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.BobInfoResponse
import com.gexiaobao.pigeon.app.model.bean.FeatherColorResponse
import com.gexiaobao.pigeon.app.model.bean.LoftMemberResponse
import com.gexiaobao.pigeon.app.model.bean.PigeonBean
import com.gexiaobao.pigeon.app.model.param.ShedRingInfoParams
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.ActivityShedAddPigneonBinding
import com.gexiaobao.pigeon.ui.dialog.DialogPigeonMasterName
import com.gexiaobao.pigeon.ui.dialog.RxMemberListDialog
import com.gexiaobao.pigeon.ui.dialog.RxShedListDialog
import com.gexiaobao.pigeon.viewmodel.ShedPigeonViewModel
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import java.io.File
import java.util.Locale

/**
 * @Author      : hxw
 * @Date        : 2024/4/12 11:31
 * @Describe    : 公棚添加赛鸽
 */
class ActivityShedAddPigeon : BaseActivity<ShedPigeonViewModel, ActivityShedAddPigneonBinding>() {

    private var mPigeonRingId: String = ""
    private var mFeatherColorStr: String = ""
    private var mPosition = 0//记录选择的羽色的position
    private var featherColorId = 0
    private var userName = ""

    private var dataResult: ArrayList<BobInfoResponse.ListData> = arrayListOf()
    private var loftMemberResult: ArrayList<LoftMemberResponse.ListData> = arrayListOf()
    private var pictureType = 0
    private var bodyPic: File? = null
    private var featherPic: File? = null
    private var leftHead: File? = null
    private var rightHeadPic: File? = null
    private var mTypeIntent = 0
    private var mPigeonId: Int = 0
    private var mWantedOrgId = 0
    private var mShedId = 0
    private lateinit var mPigeonData: PigeonBean.RingInfo

    override fun initView(savedInstanceState: Bundle?) {
        mTypeIntent = intent.getIntExtra("type", 0)
        val title = if (mTypeIntent == 1) {
            "添加赛鸽"
        } else {
            "修改赛鸽"
        }
        mDatabind.includeBar.toolbar.initClose(title) {
            finish()
        }
        mDatabind.viewmodel = mViewModel
        val userData = CacheUtil.getUser()
        if (userData != null) {
            userName = userData.realName
        }
        if (mTypeIntent == 2) {
            showUIData()
        }
        addTextWatch()
        checkedListeners()
        mViewModel.getLoftOrgListByUser()
    }

    private fun showUIData() {
        mPigeonData = intent?.getSerializableExtra("pigeonData") as PigeonBean.RingInfo
        mPigeonId = mPigeonData.pigeonId
        mFeatherColorStr = mPigeonData.featherColorStr
        mWantedOrgId = mPigeonData.wantedOrgId
        mShedId = mPigeonData.memberId
        mDatabind.etShedPigeonName.setText(mPigeonData.name)
        mPigeonRingId = mPigeonData.ringId
        mViewModel.pigeonSex.set(mPigeonData.sex.toString())
        featherColorId = mPigeonData.featherColor
        mViewModel.pigeonEyePattern.set(mPigeonData.eyePattern.toString())
        val ringId = mPigeonData.ringId.split("-")
        if (ringId.isNotEmpty() && ringId.size == 3) {
            mDatabind.layoutRingNumber.tvRingNumberYear.setText(ringId[0])
            mDatabind.layoutRingNumber.tvRingNumberArea.setText(ringId[1])
            mDatabind.layoutRingNumber.tvRingNumber.setText(ringId[2])
        }
        when (mPigeonData.sex) {
            1 -> {
                mDatabind.rbShedAddPigeonNo.isChecked = true
            }

            2 -> {
                mDatabind.rbShedAddPigeonFemale.isChecked = true
            }

            3 -> {
                mDatabind.rbShedAddPigeonMale.isChecked = true
            }
        }
        mViewModel.pigeonFeatherColor.set(mFeatherColorStr)
        when (mPigeonData.eyePattern) {
            1 -> {
                mDatabind.rbShedAddPigeonNoColor.isChecked = true
            }

            2 -> {
                mDatabind.rbShedAddPigeonYellow.isChecked = true
            }

            3 -> {
                mDatabind.rbShedAddPigeonSha.isChecked = true
            }

            4 -> {
                mDatabind.rbShedAddPigeonNiu.isChecked = true
            }
        }
        ImageLoaderManager.loadRoundImage(
            this,
            mPigeonData.bodyPicPath,
            mDatabind.ivShedPicBody,
            10
        )

        ImageLoaderManager.loadRoundImage(
            this,
            mPigeonData.featherPicPath,
            mDatabind.ivShedPicWing,
            10
        )
        ImageLoaderManager.loadRoundImage(
            this,
            mPigeonData.leftHeadPicPath,
            mDatabind.ivShedPicLeftHead,
            10
        )
        ImageLoaderManager.loadRoundImage(
            this,
            mPigeonData.rightHeadPicId,
            mDatabind.ivShedPicRightHead,
            10
        )
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.ivAddPigeonShed,
            mDatabind.tvShedAddPigeonCommit,
            mDatabind.tvShedAddPigeonColor,
            mDatabind.ivShedAddPigeonColor,
            mDatabind.rlShedPicBody,
            mDatabind.rlShedPicWing,
            mDatabind.rlShedPicLeftHead,
            mDatabind.rlShedPicRightHead,
            mDatabind.ivDeleteBodyPic,
            mDatabind.ivDeleteBodyWing,
            mDatabind.ivDeleteBodyLeftHead,
            mDatabind.ivDeleteBodyRightHead,
            mDatabind.ivChooseShed,
            mDatabind.etShedName,
            mDatabind.etMemberName,
            mDatabind.ivChooseMember,
        ) {
            when (it) {
                mDatabind.etMemberName, mDatabind.ivChooseMember -> {
                    if (mDatabind.etShedName.text.isEmpty()) {
                        RxToast.showToast("请先选择公棚")
                        return@setOnclickNoRepeat
                    }
                    showMemberDialog()
                }

                mDatabind.ivChooseShed, mDatabind.etShedName -> {
                    showShedDialog()
                }

                mDatabind.ivDeleteBodyRightHead -> {
                    mDatabind.ivShedPicRightHead.setImageBitmap(null)
                    rightHeadPic = null
                    mDatabind.ivDeleteBodyRightHead.visibility = View.GONE
                }

                mDatabind.ivDeleteBodyLeftHead -> {
                    mDatabind.ivShedPicLeftHead.setImageBitmap(null)
                    leftHead = null
                    mDatabind.ivDeleteBodyLeftHead.visibility = View.GONE
                }

                mDatabind.ivDeleteBodyWing -> {
                    mDatabind.ivShedPicWing.setImageBitmap(null)
                    featherPic = null
                    mDatabind.ivDeleteBodyWing.visibility = View.GONE
                }

                mDatabind.ivDeleteBodyPic -> {
                    mDatabind.ivShedPicBody.setImageBitmap(null)
                    bodyPic = null
                    mDatabind.ivDeleteBodyPic.visibility = View.GONE
                }

                mDatabind.rlShedPicRightHead -> {
                    pictureType = 4
                    selectBodyPic()
                }

                mDatabind.rlShedPicLeftHead -> {
                    pictureType = 3
                    selectBodyPic()
                }

                mDatabind.rlShedPicWing -> {
                    pictureType = 2
                    selectBodyPic()
                }

                mDatabind.rlShedPicBody -> {
                    pictureType = 1
                    selectBodyPic()
                }

                mDatabind.tvShedAddPigeonColor, mDatabind.ivShedAddPigeonColor -> {
                    mViewModel.getFeatherColorApp()
                }

                mDatabind.tvShedAddPigeonCommit -> {
                    val name = mDatabind.etShedPigeonName.text.toString().trim()
                    if (name != userName) {
                        KvUtils.encode("pigeonMasterName", name)
                    }
                    addPigeons()
                }

                mDatabind.ivAddPigeonShed -> {
                    showPigeonMasterName()
                }
            }
        }
    }

    private fun showMemberDialog() {
        val dialog = RxMemberListDialog(this)
        dialog.setData(loftMemberResult)
        dialog.setOnMemberNameClickListener(object : RxMemberListDialog.OnMemberNameClickListener {
            override fun onItemClick(position: Int, name: String, id: Int) {
                mDatabind.etMemberName.text = name
                mShedId = loftMemberResult[0].id
            }
        })
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun showShedDialog() {
        if (dataResult.isEmpty()) {
            RxToast.showToast("您暂未加入任何公棚")
            return
        }
        val dialog = RxShedListDialog(this)
        dialog.setData(dataResult)
        dialog.setOnShedNameClickListener(object : RxShedListDialog.OnShedNameClickListener {
            override fun onItemClick(position: Int, name: String, userId: Int, id: Int) {
                mDatabind.etShedName.text = name
                mWantedOrgId = userId
                mViewModel.getLoftMemberListByUserIdAndOrgId(id.toString(), 0)
            }
        })
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun selectBodyPic() {
        val selectionModel: PictureSelectionModel = PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(PictureSelectorStyle())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setSelectionMode(SelectModeConfig.SINGLE)
            .setCompressEngine(PictureUtil.getCompressFileEngine())
            .setCameraInterceptListener(PictureUtil.getCustomCameraEvent())
            .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
            .setPreviewInterceptListener(PictureUtil.getPreviewInterceptListener())
            .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
            .isLoopAutoVideoPlay(false)
            .isPageSyncAlbumCount(true)
            .setLanguage(LanguageConfig.SYSTEM_LANGUAGE)
            .setQuerySortOrder("")
            .isDisplayCamera(true)
            .isDirectReturnSingle(true)
            .isOpenClickSound(true)
            .isPreviewImage(false)
            .isMaxSelectEnabledMask(false)
            .setMaxSelectNum(1)
        selectionModel.forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: ArrayList<LocalMedia>?) {
                val imageFile = File(result!![0].realPath)
                when (pictureType) {
                    1 -> {
                        mDatabind.ivDeleteBodyPic.visibility = View.VISIBLE
                        bodyPic = imageFile
                        mDatabind.ivShedPicBody.setImageURI(Uri.parse("file://" + result[0].realPath))
                    }

                    2 -> {
                        mDatabind.ivDeleteBodyWing.visibility = View.VISIBLE
                        featherPic = imageFile
                        mDatabind.ivShedPicWing.setImageURI(Uri.parse("file://" + result[0].realPath))
                    }

                    3 -> {
                        mDatabind.ivDeleteBodyLeftHead.visibility = View.VISIBLE
                        leftHead = imageFile
                        mDatabind.ivShedPicLeftHead.setImageURI(Uri.parse("file://" + result[0].realPath))
                    }

                    4 -> {
                        mDatabind.ivDeleteBodyRightHead.visibility = View.VISIBLE
                        rightHeadPic = imageFile
                        mDatabind.ivShedPicRightHead.setImageURI(Uri.parse("file://" + result[0].realPath))
                    }
                }
            }

            override fun onCancel() {}
        })
    }

    override fun createObserver() {
        super.createObserver()
        /** 修改赛鸽 */
        mViewModel.modifyPigeonPicResult.observe(this) {
            if (it.isSuccess) {
                finish()
                eventViewModel.toModifyPigeonResult.value = mPigeonId
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取用户所属公棚下会员列表 */
        mViewModel.loftMemberResult.observe(this) { it ->
            loftMemberResult.clear()
            if (!it.isEmpty()) {
                loftMemberResult.addAll(it.list)
                if (loftMemberResult.size == 1) {
                    mDatabind.etMemberName.text = loftMemberResult[0].name
                    mShedId = loftMemberResult[0].id
                }
                it.list.forEach {
                    if (mShedId == it.id) {
                        mDatabind.etMemberName.text = it.name
                    }
                }
            }
        }
        /** 添加赛鸽 */
        mViewModel.createPigeon.observe(this) {
            dismissLoading()
            if (it.isSuccess) {
                eventViewModel.toRefreshData.value = true
                finish()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取用户所属公棚列表 */
        mViewModel.BobInfoResult.observe(this) { it ->
            dataResult.clear()
            if (!it.isEmpty()) {
                dataResult.addAll(it.list)
                if (dataResult.size == 1) {
                    mDatabind.etShedName.text = dataResult[0].name
                    mWantedOrgId = dataResult[0].userId
                    mViewModel.getLoftMemberListByUserIdAndOrgId(dataResult[0].id.toString(), 0)
                }
                it.list.forEach {
                    if (mWantedOrgId == it.userId) {
                        mDatabind.etShedName.text = it.name
                        mViewModel.getLoftMemberListByUserIdAndOrgId(it.id.toString(), 0)
                    }
                }
            }
        }
        /** 获取羽色列表 */
        mViewModel.featherColor.observe(this) {
            if (it.isSuccess) {
                pigeonFeatherColor(it.listData)
            } else {
                RxToast.showToast(it.errMessage)
            }
        }
    }

    private fun addTextWatch() {
        mDatabind.layoutRingNumber.tvRingNumberYear.addTextChangedListener {
            if (it?.length == 4) {
                mDatabind.layoutRingNumber.tvRingNumberArea.requestFocus()
            }
        }

        mDatabind.layoutRingNumber.tvRingNumberArea.addTextChangedListener {
            if (it?.length == 2) {
                mDatabind.layoutRingNumber.tvRingNumber.requestFocus()
            }
        }
    }

    private fun checkedListeners() {
        mDatabind.rbShedAddPigeonNo.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonSex.set("1")
        }

        mDatabind.rbShedAddPigeonMale.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonSex.set("3")

        }
        mDatabind.rbShedAddPigeonFemale.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonSex.set("2")
        }
        mDatabind.rbShedAddPigeonNoColor.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonEyePattern.set("1")
        }

        mDatabind.rbShedAddPigeonYellow.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonEyePattern.set("2")
        }

        mDatabind.rbShedAddPigeonSha.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonEyePattern.set("3")
        }

        mDatabind.rbShedAddPigeonNiu.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonEyePattern.set("4")
        }
    }

    private fun addPigeons() {
        val yearRingNum = mDatabind.layoutRingNumber.tvRingNumberYear.text.toString().trim()
        val areaRingNum = mDatabind.layoutRingNumber.tvRingNumberArea.text.toString().trim()
        val ringNum = mDatabind.layoutRingNumber.tvRingNumber.text.toString().trim()
        when {
            mWantedOrgId == 0 -> showMessage("请选择公棚")
            mShedId == 0 -> showMessage("请选择公棚下会员")
            mDatabind.etShedPigeonName.text.toString().isEmpty() -> showMessage("请填写鸽主或寄养人名称")
            yearRingNum.isEmpty() || yearRingNum.length != 4 -> showMessage("足环号年份不正确")
            areaRingNum.isEmpty() || areaRingNum.length != 2 -> showMessage("足环号地区不正确")
            ringNum.isEmpty() -> showMessage("请填写正确足环号")
            mViewModel.pigeonSex.get().isEmpty() -> showMessage("请选择赛鸽性别")
            mViewModel.pigeonFeatherColor.get().isEmpty() -> showMessage("请选择羽色")
            mViewModel.pigeonEyePattern.get().isEmpty() -> showMessage("请选择眼沙")
            else -> {
                mPigeonRingId = "$yearRingNum-$areaRingNum-$ringNum"
                if (mTypeIntent == 1) {
                    val bean = ShedRingInfoParams(
                        wantedOrgId = mWantedOrgId,
                        memberId = mShedId,
                        fosterName = mDatabind.etShedPigeonName.text.toString().trim(),
                        ringId = mPigeonRingId.uppercase(Locale.getDefault()),
                        sex = mViewModel.pigeonSex.get().toInt(),
                        featherColor = featherColorId,
                        eyePattern = mViewModel.pigeonEyePattern.get().toInt(),
                        bodyPic = bodyPic,
                        featherPic = featherPic,
                        leftHead = leftHead,
                        rightHeadPic = rightHeadPic,
                    )
                    showLoading(getString(R.string.loading))
                    mViewModel.createPigeon(bean)
                } else {
                    val bean = ShedRingInfoParams(
                        wantedOrgId = mWantedOrgId,
                        memberId = mShedId,
                        id = mPigeonId,
                        fosterName = mDatabind.etShedPigeonName.text.toString().trim(),
                        ringId = mPigeonRingId.uppercase(Locale.getDefault()),
                        sex = mViewModel.pigeonSex.get().toInt(),
                        featherColor = featherColorId,
                        eyePattern = mViewModel.pigeonEyePattern.get().toInt(),
                        bodyPic = bodyPic,
                        featherPic = featherPic,
                        leftHead = leftHead,
                        rightHeadPic = rightHeadPic,
                    )
                    mViewModel.updateLoftPigeonForUser(bean)
                }
            }
        }
    }

    private fun showPigeonMasterName() {
        val name = KvUtils.decodeString("pigeonMasterName")
        val dialog = DialogPigeonMasterName(this)
        dialog.setName1(name)
        dialog.setName2(userName)
        dialog.setName1Listener {
            mDatabind.etShedPigeonName.setText(dialog.getName1Text())
            mDatabind.etShedPigeonName.setSelection(mDatabind.etShedPigeonName.length())
            dialog.dismiss()
        }
        dialog.setName2lListener {
            mDatabind.etShedPigeonName.setText(dialog.getName2Text())
            mDatabind.etShedPigeonName.setSelection(mDatabind.etShedPigeonName.length())
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun pigeonFeatherColor(listData: ArrayList<FeatherColorResponse.ColorList>?) {
        val flyKey: ArrayList<String> = arrayListOf()
        if (listData != null && listData.size != 0) {
            for (item in listData) {
                flyKey.add(item.featherColor)
            }
            for ((index, item) in listData.withIndex()) {
                if (item.featherColor == mFeatherColorStr) {
                    mPosition = index
                    break
                } else {
                    mPosition = 2
                }
            }
        }

        val picker = OptionPicker(this, flyKey)
        val params = picker.window.attributes
        params.width = this.windowManager?.defaultDisplay!!.width
        picker.setCanceledOnTouchOutside(false)
        picker.setDividerRatio(WheelView.DividerConfig.FILL)
        picker.setShadowColor(ContextCompat.getColor(this, R.color.bg_light_bllue), 40)
        picker.selectedIndex = mPosition
        picker.setCycleDisable(true)
        picker.setTitleText("请选择羽色")
        picker.setTitleTextColor(Color.BLACK)
        picker.setTitleTextSize(18)
        picker.setSubmitText("确认")
        picker.setSubmitTextSize(17)
        picker.setSubmitTextColor(ContextCompat.getColor(this, R.color.bg_light_bllue))//确定按钮文字颜色
        picker.setCancelText("取消")
        picker.setCancelTextSize(17)
        picker.setCancelTextColor(ContextCompat.getColor(this, R.color.bg_light_bllue))//取消按钮文字颜色
        picker.setTextSize(18)
        picker.setLineSpaceMultiplier(3.0F)
        picker.setOnOptionPickListener(object : OptionPicker.OnOptionPickListener() {
            override fun onOptionPicked(index: Int, item: String) {
                mViewModel.pigeonFeatherColor.set(item)
                mViewModel.pigeonFeatherColorPosition.set(index + 1)
                mPosition = index
                featherColorId = listData?.get(index)!!.id
            }
        })
        picker.show()
    }
}